package cn.xyt.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.netty.channel.Channel;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class DeviceCache {
	private static final Logger LOG = LoggerFactory.getLogger(DeviceCache.class);
	private static Cache<String, Channel> cache = null;

	public static Channel get(String key) {
		Channel channel = null;
		try {
			channel = (Channel) cache.getIfPresent(key);
		} catch (Exception e) {
			LOG.debug("get device socket[sn={}] from cache faild, error={}", key, e.getMessage());
		}
		return channel;
	}

	public static void set(String key, Channel channel) {
		cache.put(key, channel);
	}

	public static Map<String, Channel> asMap(){
		return cache.asMap();
	}
	
	public static Cache<String, Channel> cache(){
		return cache;
	}
	
	public static void remove(String key) {
		try {
			cache.invalidate(key);
		} catch (Exception e) {
			LOG.debug("remove device[sn={}] from cache faild, error={}", key, e.getMessage());
		}
	}
	
	public static boolean containsValue(Object value){
		return cache.asMap().containsValue(value);
	}

	@PostConstruct
	public void init() {
		if (cache == null) {
			cache = CacheBuilder.newBuilder().build();
		}
	}

	@PreDestroy
	public void destroy() {
		try {
			cache.invalidateAll();
		} catch (Exception e) {
			LOG.debug("remove all from cache faild, error={}", e.getMessage());
		}
	}
}
